﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

using Seven.Entity;
using Seven.EntityBasic;
using Seven.DataModel.ViewModels.DeskModuleAbout;
using Seven.Tools.Extension;

namespace Seven.Service.Powerful
{
    public partial class SysUserDeskModuleService
    {
        #region 获取ViewModel

        /// <summary>
        /// 根据主键ID获取供编辑的数据模型
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns></returns>
        public UserDeskModuleModel GetEditModel(int id)
        {
            using (var unit = DbFactory.UnitOfWork)
            {
                var rep = unit.SysUserDeskModule;
                var model = rep.GetEditModelByID(id);

                return model;
            }
        }

        #endregion

        /// <summary>
        /// 根据用户ID获取该用户有权限的桌面模块数据模型
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="menuIds">用户的菜单范围的ID集合，用于桌面模块关联菜单的权限判定</param>
        /// <returns></returns>
        public IEnumerable<UserDeskModuleModel> UseableDeskModules(int userId, IEnumerable<int> menuIds)
        {
            using (var unit = DbFactory.UnitOfWork)
            {
                var rep = unit.SysUserDeskModule;
                var data = rep.GetUserDeskModuleModels(userId).Where(w => w.MenuID == 0 || menuIds.Contains(w.MenuID));
                foreach (var item in data.Where(w => !string.IsNullOrWhiteSpace(w.Url)))
                { item.Url = "/Desk/" + item.Url; }
                return data;
            }
        }

        /// <summary>
        /// 获取当前用户用户有权限的桌面模块数据模型
        /// </summary>
        /// <returns></returns>
        public IEnumerable<UserDeskModuleModel> CurrentUserUseableDeskModules()
        {
            return this.UseableDeskModules(CurrentUserBaseInfo.UserID, CurrentUserMenuRange.Select(s => s.ID));
        }

        #region 提供json数据

        /// <summary>
        /// 根据用户ID获取该用户的桌面模块权限数据
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns></returns>
        public JsonResult UserDeskModulePermissionJson(int userId)
        {
            IEnumerable<int> deskModuleIDs;
            IEnumerable<SysDeskModule> deskModules;
            using (var unit = DbFactory.UnitOfWork)
            {
                var rep = unit.SysUserDeskModule;
                deskModuleIDs = rep.GetDeskModuleIDs(userId);
                //若当前用户是超管，则显示所有桌面模块以供配置权限；若不是则显示“当前用户所能管理的桌面模块以供配置权限”
                if (CurrentUserBaseInfo.UserName.Equals(SiteCore.DefaultSuperAdminAccountName, StringComparison.InvariantCultureIgnoreCase))
                { deskModules = unit.SysDeskModule.GetUseableDeskModules(); }
                else
                { deskModules = rep.GetDeskModules(CurrentUserBaseInfo.UserID); }
            }

            var data = deskModules.Select(s => new { s.ID, s.Name, s.SortNumber, s.Location, Permission = deskModuleIDs.Contains(s.ID) });

            return new DataResult(data).SerializeToJsonResult();
        }

        /// <summary>
        /// 获取指定用户的指定位置的桌面模块列表数据
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="location">位置，值可以是 left 或者 right</param>
        /// <returns></returns>
        public JsonResult UserDeskModuleGrid(int userId, string location)
        {
            using (var unit = DbFactory.UnitOfWork)
            {
                DeskModuleLocation l = location.Equals("left", StringComparison.InvariantCultureIgnoreCase) ? DeskModuleLocation.左边 : DeskModuleLocation.右边;
                var data = unit.SysUserDeskModule.GetUserDeskModuleModels(userId, l, true);
                return new DataResult(data).SerializeToJsonResult(true);
            }
        }

        /// <summary>
        /// 一次性获取指定用户的桌面模块列表数据，返回的数据中以left和right属性区分。
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns></returns>
        public JsonResult UserDeskModuleJsonForOnce(int userId)
        {
            using (var unit = DbFactory.UnitOfWork)
            {
                var data = unit.SysUserDeskModule.GetUserDeskModuleModels(userId, null, true);
                var left = data.Where(w => w.Location == DeskModuleLocation.左边);
                var right = data.Where(w => w.Location == DeskModuleLocation.右边);
                return new DataResult(new { left = left, right = right }).SerializeToJsonResult(true);
            }
        }

        #endregion

        #region CUD操作

        /// <summary>
        /// 保存用户桌面权限
        /// </summary>
        /// <param name="deskModuleIds">桌面模块IDs，以“,”相连</param>
        /// <param name="userId">用户ID</param>
        /// <returns></returns>
        public JsonResult SaveUserDeskModulePermission(string deskModuleIds, int userId)
        {
            OperationResult result;
            using (var unit = DbFactory.UnitOfWork)
            {
                var rep = unit.SysUserDeskModule;

                IEnumerable<SysUserDeskModule> userDeskModules = rep.GetUserDeskModules(userId, true);
                IList<SysUserDeskModule> inserts = new List<SysUserDeskModule>(), updates = new List<SysUserDeskModule>();
                var ids = deskModuleIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToInt();

                foreach (var item in userDeskModules)
                {
                    if (ids.Contains(item.DeskModuleID))
                    {
                        if (item.IsDisabled) { item.IsDisabled = false; updates.Add(item); }
                    }
                    else
                    { if (!item.IsDisabled) { item.IsDisabled = true; updates.Add(item); } }
                }
                var existIds = userDeskModules.Select(s => s.DeskModuleID);
                foreach (var item in unit.SysDeskModule.GetDeskModules(ids.Except(existIds)))
                {
                    inserts.Add(new SysUserDeskModule
                    {
                        UserID = userId,
                        DeskModuleID = item.ID,
                        Location = item.Location,
                        Height = item.Height,
                        Size = item.Size,
                        SortNumber = item.SortNumber,
                        ReceiveMessage = item.ReceiveMessage,
                        IsShow = true
                    });
                }

                rep.EntitiesModified(updates);
                rep.EntitiesAdded(inserts);

                var msg = new string[] { "保存成功!", "保存失败!" };
                result = new OperationResult(unit.Commit() > 0, msg);
            }

            return result.SerializeToJsonResult();
        }

        /// <summary>
        /// 保存用户桌面模块
        /// </summary>
        /// <param name="model">用户桌面模块设置数据模型</param>
        /// <returns>操作结果</returns>
        public JsonResult SaveUserDeskModule(UserDeskModuleModel model)
        {
            SysUserDeskModule entity = this.GetByKey(model.ID);

            entity.Location = model.Location;
            entity.SortNumber = model.SortNumber;
            entity.Size = model.Size;
            entity.Height = model.Height;
            entity.ReceiveMessage = model.ReceiveMessage;
            entity.IsShow = model.IsShow;

            return this.Update(entity).SerializeToJsonResult();
        }

        #endregion
    }
}
